package com.culture.java.online.education.platform.data.demo.validate.handler;

import com.culture.java.online.education.platform.data.demo.validate.BirthdayAgeValidated;
import com.culture.java.online.education.platform.data.demo.vo.input.StudentSaveOrModifyVo;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class BirthdayAgeValidatedHandler implements ConstraintValidator<BirthdayAgeValidated, StudentSaveOrModifyVo> {

    @Override
    public boolean isValid(StudentSaveOrModifyVo student, ConstraintValidatorContext constraintValidatorContext) {
        if (student.getBirthday() == null || student.getAge() == null) {
            return true;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar birthday = Calendar.getInstance();

        LocalDate localDateBirthday = student.getBirthday();
        Date dateBirthday = Date.from(localDateBirthday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        birthday.setTime(dateBirthday);

        int calendarYear = calendar.get(Calendar.YEAR);
        int birthdayYear = birthday.get(Calendar.YEAR);
        if (calendarYear - birthdayYear == student.getAge()) {
            return true;
        }
        return false;
    }

}
